package cn.dlc.com.order.config;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.fastjson.JSON;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
 * @author 邓立川
 * @date 2020/12/31 15:31
 * @desc 自定义异常处理类
 */
@Component
public class ExceptionHandlerPage implements UrlBlockHandler {

    /**
     *
     * @param request
     * @param response
     * @param e 通过e来捕获异常，他有五个子类，分别对应五个规则
      *          AuthorityException： 对应授权规则
      *          DegradeException：对应降级规则
      *          FlowException：对应流控规则
      *          ParamFlowException：对应热点规则
      *          SystemBlockException：对应系统规则
      * @throws IOException
     */
    @Override
    public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException e) throws IOException {

        // 防止中文乱码
        response.setHeader("Content-type","application/json;charset=utf-8");

        ResponseData data = null;
        if(e instanceof FlowException) {
            data = new ResponseData(-1,"流控了..");
        } else if(e instanceof DegradeException){
            data = new ResponseData(-2,"降级了..");
        } else if (e instanceof AuthorityException){
            data = new ResponseData(-2,"权限管理..");
        }
        // 相应给前端
        response.getWriter().write(JSON.toJSONString(data));
    }
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class ResponseData{
    private int code;
    private String msg;

}